//
//  NewsDetailViewController.m
//  DaJiang
//
//  Created by sally on 16/10/1.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "NewsDetailCell.h"
#import "NewsDetailPicCell.h"
#import "NewsDetailViewController.h"
#import "ChatExtDB.h"
#import "ChatManager.h"

#define TextViewDefaultHeight 35                                        //输入框中textView的原始高度
#define InputViewDefaultHeight 49                                       //输入框的原始高度
#define TableDefaultHeight (ScreenHeight - 64 - InputViewDefaultHeight) //table的高度

@interface NewsDetailViewController () <UITextViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate,IChatManagerDelegate>{
  //缓冲圈相关
  UIView *headView;
  UIActivityIndicatorView *activity;
  BOOL isRefresh; //是否刷新
  BOOL isNoMore; //没有更多聊天信息
  BOOL isInvisible; //是否置为未读
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHeightLyt;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewHeightLyt;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableHeightLayout;
@property (strong, nonatomic) NSMutableArray *tableData;
@property (assign, nonatomic) long     long               timestamp;

@end

@implementation NewsDetailViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
  [self registerNotifications];
  [self initControl];
  [self initData];
  [self loadRefreshData];
}

-(void)viewDidAppear:(BOOL)animated{
  isInvisible = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  isInvisible = NO;
}

- (void)dealloc {
  [self unregisterNotifications];
}

#pragma mark 初始化控件
- (void)initControl {
  self.title = @"某某人";
  self.tableHeightLayout.constant = TableDefaultHeight;
  
  self.textView.layer.borderColor = kGetColor(221, 221, 221).CGColor;
  self.textView.layer.borderWidth = 1.0;
  self.textView.layer.cornerRadius = GLargeCornerRadius;
  self.textView.returnKeyType = UIReturnKeySend; //键盘显示发送
  self.textView.delegate = self;
  
  ChatExtDB *extDb = [ChatExtDB queryExtByUserName:self.conversation.chatter];
  if (extDb) {
    self.userName = extDb.nickname;
  }
  self.navigationItem.title = self.userName;
  
  //缓冲圈
  headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
  headView.backgroundColor = [UIColor clearColor];
  activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
  [headView addSubview:activity];
  activity.frame = CGRectMake(headView.frame.size.width / 2, headView.frame.size.height / 2, 20, 20);
  self.tableView.tableHeaderView = headView;
  headView.hidden = YES;
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [[NSMutableArray alloc] init];
  isNoMore = NO;
  
  //  //FIXME: 运行后第一次进入页面，并没有及时滑至最底部，应该跟table装配有时间差有关系。
  //  [self tableViewScrollCurrentIndexWithAnimate:NO];
}

#pragma mark - 加载数据
- (void)loadRefreshData {
  self.timestamp = [[NSDate date] timeIntervalSince1970] * 1000 + 1;
  [self loadDataWithPage:self.timestamp isMore:NO];
}

- (void)loadMoreData {
  //显示缓冲圈
  headView.hidden = NO;
  [activity startAnimating];
  isRefresh = YES;
  
  //刷新是延时1秒出数据，不然数据出现太快
  [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(loadMoreDataAfterTimer) userInfo:nil repeats:NO];
}

- (void)loadMoreDataAfterTimer {
  EMMessage *firstMessage = [self.tableData firstObject];
  if (firstMessage) {
    [self loadDataWithPage:firstMessage.timestamp isMore:YES];
  }
}

- (void)loadDataWithPage:(long long)timestamp isMore:(BOOL)isMore {
  __weak typeof(self) weakSelf = self;
  NSArray *messages = [weakSelf.conversation loadNumbersOfMessages:GListCount before:timestamp];
  
  if (messages) {
    //标志已读
    [self.conversation markAllMessagesAsRead:YES];
    
    // 刷新数据
    if (!isMore) {
      if (messages.count > 0) {
        [self.tableData removeAllObjects];
        self.tableData = [messages mutableCopy];
        [self.tableView reloadData];
        [self scrollToBottom];
        
        if (messages.count < GListCount) {
          isNoMore = YES;
        }
      }
    }
    // 加载更多
    else {
      if (messages.count > 0) {
        NSRange range = NSMakeRange(0, [messages count]);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.tableData insertObjects:messages atIndexes:indexSet];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:messages.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        
        if (messages.count < GListCount) {
          isNoMore = YES;
        }
      } else {
        isNoMore = YES;
      }
      //隐藏缓冲圈
      [activity stopAnimating];
      headView.hidden = YES;
      isRefresh = NO;
    }
    
  } else {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"无更多数据"];
  }
  
  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}


- (IBAction)actionOnCamera:(id)sender {
  [self.textView resignFirstResponder];
  [OperationManager configCameraActionSheet];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.tableData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  EMMessage *message = self.tableData[indexPath.row];
  id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
  
  if (msgBody.messageBodyType == eMessageBodyType_Image) {//图片类型
    return [NewsDetailPicCell cellHeight];
    
  }else{
    //只创建一个cell用作测量高度
    static NewsDetailCell *cell = nil;
    if (!cell) {
      [self.tableView registerNib:[UINib nibWithNibName:@"NewsDetailCell" bundle:nil] forCellReuseIdentifier:@"NewsDetailCell"];
      cell = [self.tableView dequeueReusableCellWithIdentifier:@"NewsDetailCell"];
    }
    
    cell.cellMsgData = message;
    return [self getCellHeight:cell];
  }
}

- (CGFloat)getCellHeight:(UITableViewCell *)cell {
  [cell layoutIfNeeded];
  [cell updateConstraintsIfNeeded];
  
  CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
  return height + 1.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  EMMessage *message = self.tableData[indexPath.row];
  id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
  
  if (msgBody.messageBodyType == eMessageBodyType_Image) {//图片类型
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsDetailPicCell" bundle:nil] forCellReuseIdentifier:@"NewsDetailPicCell"];
    NewsDetailPicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsDetailPicCell"];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.cellMsgData = self.tableData[indexPath.row];
    return cell;
  } else {//文本
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsDetailCell" bundle:nil] forCellReuseIdentifier:@"NewsDetailCell"];
    NewsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsDetailCell"];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.cellMsgData = self.tableData[indexPath.row];
    return cell;
  }
}

#pragma mark - EMChatManagerChatDelegate
#pragma mark 收到(在线)消息时的回调
- (void)didReceiveMessage:(EMMessage *)message {
  if ([self.conversation.chatter isEqualToString:message.conversationChatter]) {
    //标记已读（先回调会话列表页然后才回调聊天页，所以需要在聊天页中对收到的消息进行单个标记已读）
    [self markMessagesAsRead:message];
    
    //添加新发消息到聊天列表
    [self addMessageToTableData:message];
  }
}

#pragma mark 接收到离线非透传消息的回调
- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages {
}

#pragma mark - scrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  if (!isNoMore && scrollView.contentOffset.y <= 0 && isRefresh == NO) {
    [self loadMoreData];
  }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  [self.view endEditing:YES];
}


#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
  //发消息时，页面滚至最底部
  [self tableViewScrollCurrentIndexWithAnimate:YES];
}

- (void)textViewDidChange:(UITextView *)textView {
  //输入框，根据文字的行数加高，但最高限制于5行文字
  CGSize contentSize = textView.contentSize;
  CGFloat y = contentSize.height - TextViewDefaultHeight;
  y = y > 0 ? y : 0;
  
  if (y > 0 && y < 71) { //71为textView达到五行时的高度
    self.tableHeightLayout.constant = TableDefaultHeight - y;
    self.inputViewHeightLyt.constant = InputViewDefaultHeight + y;
    textView.height = contentSize.height;
    [self tableViewScrollCurrentIndexWithAnimate:NO];
  } else {
    CGSize textviewSize = textView.bounds.size;
    CGFloat height = contentSize.height - textviewSize.height; //上滑高度
    CGPoint offSet = CGPointMake(0, height);
    [textView setContentOffset:offSet];
  }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  //键盘实现发送操作
  if ([@"\n" isEqualToString:text] == YES) {
    
    if (self.textView.text.length == 0) {
      [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"发送内容不能为空哦"];
    } else {
      [textView resignFirstResponder];
      self.tableHeightLayout.constant = TableDefaultHeight;
      self.inputViewHeightLyt.constant = InputViewDefaultHeight;
      textView.height = TextViewDefaultHeight;
      NSString *content = self.textView.text;
      self.textView.text = @"";
      
      //发送文本消息
      [self sendMsgWithContent:content image:nil];
    }
    return NO;
  }
  return YES;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  NSString *selectStr = [actionSheet buttonTitleAtIndex:buttonIndex];
  UIImagePickerController *imagePicker = [OperationManager configImagePicker:selectStr];
  if (!imagePicker) {
    return;
  }
}

#pragma mark UIImagePickerControllerDelegate 选照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
  [picker dismissViewControllerAnimated:YES completion:nil];
  
  //选择照片
  UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
  originalImage = [[CommonMethod sharedCommonMethod] compressImage:originalImage]; //压缩图片
  
  if (originalImage) {
    //发送图片消息
    [self sendMsgWithContent:nil image:originalImage];
  }
  
  [self.tableView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 私有方法
#pragma mark 滚动到当前行
- (void)tableViewScrollCurrentIndexWithAnimate:(BOOL)animate {
  if (self.tableData.count > 0) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.tableData.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:animate];
  }
}

- (void)scrollToBottom{
  CGFloat yOffset = 0;
  
  if (self.tableView.contentSize.height > self.tableView.bounds.size.height) {
    yOffset = self.tableView.contentSize.height - self.tableView.bounds.size.height;
  }
  if (yOffset < 0) {
    yOffset = -yOffset;
  }
  
  [self.tableView setContentOffset:CGPointMake(self.tableView.frame.origin.x, yOffset + 64 + 46 +30) animated:NO];// 64为导航与状态栏的尺寸，46为另外一个view的尺寸，按需求调整
}

#pragma mark 注册delegate
- (void)registerNotifications {
  [self unregisterNotifications];
  [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)unregisterNotifications {
  [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

#pragma mark 指定消息标记已读
- (void)markMessagesAsRead:(EMMessage *)message {
  if (isInvisible) {//只有在聊天页里面时才标记已读，如果是会话页则仍是未读
    EMConversation *conversation = _conversation;
    [conversation markMessageWithId:message.messageId asRead:YES];
  }
}

#pragma mark 发送消息
- (void)sendMsgWithContent:(NSString *)content image:(UIImage *)image{
  //ext:发送者的昵称和头像URL
  UserModel *userModel = [[CacheManager shareInstance] getLastLoginAccount];
  NSMutableDictionary *extDic = [[NSMutableDictionary alloc]init];
  [extDic setJsonValue:userModel.user_data.user_profile_pic key:@"avatar"];
  extDic[@"uid"] = @(userModel.uid);
  [extDic setJsonValue:userModel.user_data.user_name key:@"nickname"];
  
  EMMessage *msg;
  if (image) {
    //发送图片消息
    msg = [ChatManager sendImageMessageWithImage:image to:self.conversation.chatter messageType:eMessageTypeChat requireEncryption:NO messageExt:extDic progress:nil];
  }else{
    //发送文本消息
    msg = [ChatManager sendTextMessage:content to:self.conversation.chatter messageType:eMessageTypeChat requireEncryption:NO messageExt:extDic];
  }
  
  //添加新发消息到聊天列表
  [self addMessageToTableData:msg];
}

#pragma mark 添加消息到tabledata
- (void)addMessageToTableData:(EMMessage *)message {
  [self.tableData addObject:message];
  [self.tableView reloadData];
  [self tableViewScrollCurrentIndexWithAnimate:NO];
}

@end
